package com.huaqin.obeacons.utils;

import org.android.agoo.client.BaseConstants;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.huaqin.obeacons.MainTabActivity;
import com.huaqin.obeacons.R;
import com.umeng.common.message.Log;
import com.umeng.message.UTrack;
import com.umeng.message.UmengBaseIntentService;
import com.umeng.message.entity.UMessage;

/**
 * @author xiabing  获取推送消息服务 友盟网站：http://www.umeng.com 账户：chaoyongan@gmail.com
 *         密码：obeacons
 */
public class MyPushIntentService extends UmengBaseIntentService {
	private static final String TAG = "blueberry";
	private NotificationManager nm;
	private Context contexts;
	int notification_id = 19172439;
	private String content;
	private String title;
	private String ticker;
	
	@Override
	protected void onMessage(Context context, Intent intent) {
		super.onMessage(context, intent);
		contexts=context;
		try {
			String message = intent.getStringExtra(BaseConstants.MESSAGE_BODY);
			UMessage msg = new UMessage(new JSONObject(message));
			UTrack.getInstance(context).trackMsgClick(msg);
			JSONObject json = new JSONObject(message);
			System.out.println("blueberry_json=" + json);

			if(json!=null){
				content = json.getJSONObject("body").getString("text");
				title = json.getJSONObject("body").getString("title");
				ticker = json.getJSONObject("body").getString("ticker");
				System.out.println("blueberry_name=" + content + " " + title + " "
						+ ticker);
			}
			
			if(content!=null && title!=null && ticker!=null){
				if(!SharedPreferenceUtil.accountIsEmpty(getApplicationContext())){
					showNewsforUpdate(title,content);
					Log.d("xiabing", "onMessage");
				    MyDatabaseUtil.insertDataFromumeng(context, title, content);		
				}				
			}			
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
	}

	// 更新完数据消息提醒
	protected void showNewsforUpdate(String title,String content) {
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		showNotification(R.drawable.notifaction_obeacons, "更新消息", ""+title, ""+content);
	}

	// 状态栏显示
	public void showNotification(int icon, String tickertext, String title,
			String content) {
		Notification notification = new Notification(icon, tickertext,
				System.currentTimeMillis());
		notification.defaults = Notification.DEFAULT_ALL;
		PendingIntent pt = PendingIntent.getActivity(this, 0, new Intent(this,
				MainTabActivity.class), 0);
		notification.setLatestEventInfo(this, title, content, pt);
		nm.notify(notification_id, notification);
	}
}


// blueberry_json={"msg_id":"us39655140387456105510",
// "body":{"play_vibrate":"true",
// "text":"sdsfsd",
// "title":"xiaobing",
// "ticker":"xiaobing",
// "play_lights":"true",
// "play_sound":"true",
// "after_open":"go_app","activity":"","url":"","custom":""},"random_min":0,"alias":"","display_type":"notification"}
